package com.diandireader.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.diandireader.activity.R;
import com.diandireader.domain.DiandiReaderVO;
import com.diandireader.util.ActivityManager;
import com.diandireader.util.FileHelper;

/**
 * 阅读器LIST页面
 * @author mayh
 *
 */
public class MainReaderListActivity extends Activity {

	private ListView bookListView;
	private List<File> bookFileList;
	private Handler handler;
	private BooksListAdapter adapter ;
	private int viewType = 1;//0:列表,1:视图
	private Resources resource;
	private ImageView listBar;
	private SharedPreferences preference,bookPositionPreference;
	private File currentFile;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//      去掉标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
//      去掉状态栏
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.reader_main_list);
		ActivityManager.add(this);
		setViews();
		setListener();
		preference = getSharedPreferences(DiandiReaderVO.SETTING, Context.MODE_PRIVATE);
		bookPositionPreference = getSharedPreferences(DiandiReaderVO.BOOKPOSITION, Context.MODE_PRIVATE);
		resource = getResources();
//		resource.getDrawable(id);
		handler = new BooksHandler();
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		Editor edit = preference.edit();
		edit.putString(DiandiReaderVO.VIEWTYPE, DiandiReaderVO.VIEWTYPE_LSIT);
		edit.commit();
		new BookListThread().start();
	}

	//设置View
	public void setViews(){
		bookListView = (ListView)findViewById(R.id.booklistview_list);
		bookListView.setClickable(true);  
		bookListView.setFocusable(true);  
		bookListView.setFocusableInTouchMode(true);  
		listBar = (ImageView)findViewById(R.id.listbar_list);
		listBar.setImageResource(R.drawable.list_bar_list_selector);
	}
	//设置Listener
	public void setListener(){
		//Item的点击监听
		bookListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) {
			    File file = bookFileList.get(position);
			    //将不支持的格式过滤掉
			    String fileType = FileHelper.getFileSuffix(file);
				if(!FileHelper.allowTypeList.contains(fileType)){
					Toast.makeText(MainReaderListActivity.this, "暂不支持该格式", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent();
				intent.putExtra("filePath", file.getPath());
				intent.setClass(MainReaderListActivity.this, SimpleTextReaderActivity.class);
				startActivity(intent);
			}
			
		});
		//创建上下文菜单
		bookListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("选择操作");
				menu.add(0, 0, 0, "删除");
			}
		});
		//创建长按
		bookListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
					int position, long id) {
				currentFile = bookFileList.get(position);
				return false;
			}
			
		});
		listBar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setClass(MainReaderListActivity.this, MainReaderIconActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}
	
	//书籍列表的Adapter
	class BooksListAdapter extends BaseAdapter {

		private Context context;
		private List<File> list;
		
		public BooksListAdapter(Context context,List<File> list){
			this.context = context;
			this.list = list;
		}
		
		@Override
		public int getCount() {
			if(list==null)
				return 0;
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			if(list==null)
				return null;
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
		
			return 0;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			File file = list.get(position);
			String fileName = "";
			String createTime = "";
			if(file!=null){
				fileName = file.getName();
				createTime = FileHelper.getFileModifyTime(file);
			}
			view = View.inflate(context, R.layout.booklistitem, null);
			Book.name = (TextView)view.findViewById(R.id.bookname);
			Book.createTime = (TextView)view.findViewById(R.id.createtime);
			Book.bookIcon = (ImageView)view.findViewById(R.id.bookicon);
			Book.fileSize = (TextView)view.findViewById(R.id.fileSize);
			Book.name.setText(fileName);
			Book.createTime.setText(createTime);
			Book.fileSize.setText(FileHelper.getFileSize(file));
			String type = FileHelper.getFileType(file);
			if(FileHelper.TXT==type){
				Book.bookIcon.setImageResource(R.drawable.file_txt);
			}else if(FileHelper.IMAGE==type){
				Book.bookIcon.setImageResource(R.drawable.file_jpg);
			}else if(FileHelper.PDF==type){
				Book.bookIcon.setImageResource(R.drawable.file_pdf);
			}else {
				Book.bookIcon.setImageResource(R.drawable.unknown);
			}
			return view;
		}
		
	}
	
	//重新获得book目录的文件
	public void refreshBooks(){
		bookFileList = new ArrayList<File>();
//		获得SD卡的路径
		String storgePath = FileHelper.getStrogeFolder(); 
//		获得存放Book的目录
		File bookFolder = new File(storgePath+"/"+FileHelper.diandiReaderBooks);
		if(bookFolder!=null){
			File[] books = bookFolder.listFiles();
			if(books!=null&&books.length>0){
				for(int i=0;i<books.length;i++){
					bookFileList.add(books[i]);
				}
			}
		}
	}
	
	//线程处理文件
	 class BookListThread extends Thread {
		@Override
		public void run() {
			refreshBooks();
			//search the book of other place
			Map<String,String> filePathMap = (Map<String,String>)bookPositionPreference.getAll();
			if(!filePathMap.isEmpty()){
				Set<String> set = filePathMap.keySet();
				String path = "";
				for(String name : set){
					 path = bookPositionPreference.getString(name, "");
					 if(path!=null&&!"".equals(path)){
						 File newFile = new File(path);
						 if(newFile.exists())
							 bookFileList.add(newFile);
					 }
				}
			};
			handler.sendEmptyMessage(0);
		}
		
	}
	 
	//用于减少内存开销的Book类
	static class Book {
		 public static TextView name;
		 public static TextView createTime;
		 public static ImageView bookIcon;
		 public static TextView fileSize;
	 }
	
	//handler处理
	class BooksHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0 : {
				adapter = new BooksListAdapter(MainReaderListActivity.this,bookFileList);
				bookListView.setAdapter(adapter);
			}
			break;
			case 1: {
				
			}
			break;
			}
		}
	}
	//上下文菜单
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 0 : {
			//删除
			AlertDialog.Builder dialog = new AlertDialog.Builder(MainReaderListActivity.this);
			dialog.setTitle("提示");
			dialog.setMessage("是否删除该书籍?");
			dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					return;
				}
			});
			dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					FileHelper.deleteFile(currentFile);
					//delete the preference
					bookPositionPreference.edit().remove(currentFile.getName());
					//刷新列表
					new BookListThread().start();
				}
			});
			dialog.show();
		}
		break;
		case 1 : {
			
		}
		break;
		}
		return super.onContextItemSelected(item);
	}

	//监听按键
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//监听取消按钮
		if(keyCode==KeyEvent.KEYCODE_BACK){
			AlertDialog.Builder builder = new AlertDialog.Builder(MainReaderListActivity.this);
			builder.setTitle("提示");
			builder.setMessage("确定要退出么？");
			builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					for(Activity activity : ActivityManager.list){
						if(activity!=null)
						activity.finish();
					}
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			});
			builder.show();
		}
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "选择文件");
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 0 : {
			Intent intent = new Intent();
			intent.setClass(MainReaderListActivity.this,FileBrowsActivity.class);
			startActivity(intent);
//			finish();
		}
		break;
		}
		return false;
	}
	
}
